import React, { useState, useEffect } from 'react';
import { Button, Radio, Space, message } from 'antd';
import getTime from './Calculate/index'
import './index.less';
import { apiThisWeekFreetime, apiNextWeekFreetime, upDateFreeTime } from '@/api/api'

// Freetime组件
const Freetime = () => {
  // 获取星期几
  // [  now1, now2, now3, now4, now5, next1, next2, next3, next4, next5]
  const timeArray = getTime()
  // 将日期转为后端一样的格式
  const formattedTimeArray = [];
  for (let i = 0; i < timeArray.length; i++) {
    const timeString = timeArray[i];
    const year = timeString.substr(0, 4);
    const month = timeString.substr(4, 2);
    const day = timeString.substr(6, 2);
    const formattedDate = `${year}-${month}-${day}`;
    formattedTimeArray.push(formattedDate);
  }
  const nightKeys = ['9-2', '10-2', '9-3', '10-3', '9-4', '10-4', '9-5', '10-5', '9-6', '10-6']
  const [res, setRes] = useState('')
  const [res1, setRes1] = useState('')
  const [value, setValue] = useState(1);//  1表示本周，2表示下周
  const [clickedCells, setClickedCells] = useState(nightKeys); //存储点击cell
  // 自定义内容数组
  const dates = [
    '9:00-10:00',
    '10:00-11:00',
    '11:00-12:00',
    '14:00-15:00',
    '15:00-16:00',
    '16:00-17:00',
    '17:00-18:00',
    '19:00-20:00',
    '20:00-21:00',
  ];
  useEffect(() => {
    // 请求本周数据
    apiThisWeekFreetime().then((thisWeek) => {
      setRes(thisWeek.data)
    }
    ).catch()
  }, []);
  useEffect(() => {
    // 请求下周数据
    apiNextWeekFreetime().then((nextWeek) => {
      setRes1(nextWeek.data)
    }
    ).catch()

  }, []);
  const thisCol1Data = res[0] || [];
  const thisCol2Data = res[1] || [];
  const thisCol3Data = res[2] || [];
  const thisCol4Data = res[3] || [];
  const thisCol5Data = res[4] || [];
  // 本周所有数据
  const thisWeekData = thisCol1Data.concat(thisCol2Data, thisCol3Data, thisCol4Data, thisCol5Data);
  const NextCol1Data = res1[0] || [];
  const NextCol2Data = res1[1] || [];
  const NextCol3Data = res1[2] || [];
  const NextCol4Data = res1[3] || [];
  const NextCol5Data = res1[4] || [];
  // 下周所有数据
  const nextWeekData = NextCol1Data.concat(NextCol2Data, NextCol3Data, NextCol4Data, NextCol5Data);
  // 单元格点击事件
  const handleCellClick = (cellKey) => {
    if (clickedCells.includes(cellKey)) {
      // 单元格已被点击，从数组中移除
      setClickedCells(clickedCells.filter((key) => key !== cellKey));
    } else {
      // 单元格未被点击，添加到数组中
      setClickedCells([...clickedCells, cellKey]);
    }
  };
  // 切换周
  const ToggleWeek = () => {
    const onChange = (e) => {
      setValue(e.target.value);
    };

    return (
      <div className='toggleWeek'>
        <Radio.Group onChange={onChange} value={value}>
          <Space direction="vertical">
            <Radio value={1}>本周</Radio>
            <Radio value={2}>下周</Radio>
          </Space>
        </Radio.Group>
      </div>
    );
  };
  // rowIndex判断
  const judgeRowIndex = (item) => {
    if (item.time === '9:00-10:00') {
      let rowIndex = 1
      return rowIndex
    } else if (item.time === '10:00-11:00') {
      let rowIndex = 2
      return rowIndex
    } else if (item.time === '11:00-12:00') {
      let rowIndex = 3
      return rowIndex
    } else if (item.time === '14:00-15:00') {
      let rowIndex = 4
      return rowIndex
    } else if (item.time === '15:00-16:00') {
      let rowIndex = 5
      return rowIndex
    } else if (item.time === '16:00-17:00') {
      let rowIndex = 6
      return rowIndex
    } else if (item.time === '17:00-18:00') {
      let rowIndex = 7
      return rowIndex
    } else if (item.time === '19:00-20:00') {
      let rowIndex = 8
      return rowIndex
    } else if (item.time === '20:00-21:00') {
      let rowIndex = 9
      return rowIndex
    }

  }
  // 本周colIndex判断
  const judgeThisWeekColIndex = (item) => {

    if (item.date === formattedTimeArray[0].toString()) {
      let colIndex = 1
      return colIndex
    } else if (item.date === formattedTimeArray[1].toString()) {
      let colIndex = 2
      return colIndex
    } else if (item.date === formattedTimeArray[2].toString()) {
      let colIndex = 3
      return colIndex
    } else if (item.date === formattedTimeArray[3].toString()) {
      let colIndex = 4
      return colIndex
    } else if (item.date === formattedTimeArray[4].toString()) {
      let colIndex = 5
      return colIndex
    }
  }
  // 下周colIndex判断
  const judgeNextWeekColIndex = (item) => {

    if (item.date === formattedTimeArray[5].toString()) {
      let colIndex = 1
      return colIndex
    } else if (item.date === formattedTimeArray[6].toString()) {
      let colIndex = 2
      return colIndex
    } else if (item.date === formattedTimeArray[7].toString()) {
      let colIndex = 3
      return colIndex
    } else if (item.date === formattedTimeArray[8].toString()) {
      let colIndex = 4
      return colIndex
    } else if (item.date === formattedTimeArray[9].toString()) {
      let colIndex = 5
      return colIndex
    }
  }
  // 判断日期
  const judgeTime = (rowIndex) => {
    if (rowIndex === 1) {
      let date = '9:00-10:00'
      return date
    } else if (rowIndex === 2) {
      let date = '10:00-11:00'
      return date
    } else if (rowIndex === 3) {
      let date = '11:00-12:00'
      return date
    } else if (rowIndex === 4) {
      let date = '14:00-15:00'
      return date
    } else if (rowIndex === 5) {
      let date = '15:00-16:00'
      return date
    } else if (rowIndex === 6) {
      let date = '16:00-17:00'
      return date
    } else if (rowIndex === 7) {
      let date = '17:00-18:00'
      return date
    } else if (rowIndex === 8) {
      let date = '19:00-20:00'
      return date
    } else if (rowIndex === 9) {
      let date = '20:00-21:00'
      return date
    }
  }
  // 判断日期
  const judgeThisWeekDate = (colIndex) => {
    if (colIndex === 1) {
      let date = formattedTimeArray[0].toString()
      return date
    } else if (colIndex === 2) {
      let date = formattedTimeArray[1].toString()
      return date
    } else if (colIndex === 3) {
      let date = formattedTimeArray[2].toString()
      return date
    } else if (colIndex === 4) {
      let date = formattedTimeArray[3].toString()
      return date
    } else if (colIndex === 5) {
      let date = formattedTimeArray[4].toString()
      return date
    }
  }
  const judegNextWeekDate = (colIndex) => {
    if (colIndex === 1) {
      let date = formattedTimeArray[5].toString()
      return date
    } else if (colIndex === 2) {
      let date = formattedTimeArray[6].toString()
      return date
    } else if (colIndex === 3) {
      let date = formattedTimeArray[7].toString()
      return date
    } else if (colIndex === 4) {
      let date = formattedTimeArray[8].toString()
      return date
    } else if (colIndex === 5) {
      let date = formattedTimeArray[9].toString()
      return date
    }
  }
  // 查询空闲状态点击事件
  const handleQueryButtonClick = () => {
    let updatedClickedCells = [];
    // 更新单元格的状态
    if (value === 1) {
      thisWeekData.forEach((item) => {
        let rowid = judgeRowIndex(item)
        let colid = judgeThisWeekColIndex(item)
        let cellKey = `${rowid + 1}-${colid + 1}`
        if (item.idle) {
          updatedClickedCells.push(cellKey);
        } else {
          updatedClickedCells = updatedClickedCells.filter((key) => key !== cellKey);
        }
      })
      // 更新组件状态

      setClickedCells([]);
      setClickedCells(updatedClickedCells);
      message.success('查询本周空闲时间成功')
    } else {
      nextWeekData.forEach((item) => {
        let rowid = judgeRowIndex(item)
        let colid = judgeNextWeekColIndex(item)
        let cellKey = `${rowid + 1}-${colid + 1}`

        if (item.idle) {
          updatedClickedCells.push(cellKey);
        } else {
          updatedClickedCells = updatedClickedCells.filter((key) => key !== cellKey);
        }
      })
      // 更新组件状态
      setClickedCells([]);
      setClickedCells(updatedClickedCells);
      message.success('查询下周周空闲时间成功')
    }



  };

  // 提交更新点击事件
  const handleSetStatusClick = () => {
    if (value == 1) {
      let updatedArray = [];
      let postThisWeekData = [];
      for (let colIndex = 1; colIndex <= 5; colIndex++) {
        for (let rowIndex = 1; rowIndex <= 9; rowIndex++) {
          let time = judgeTime(rowIndex)
          let date = judgeThisWeekDate(colIndex)
          const cellKey = `${rowIndex + 1}-${colIndex + 1}`;
          const idle = clickedCells.includes(cellKey) ? true : false;
          const data =
          {
            id: (thisWeekData[0].id - 1) + (colIndex - 1) * 9 + rowIndex,
            // userId: thisWeekData[0].userId,
            date: date,
            time: time,
            idle: idle
          }

          updatedArray.push(data);

          if (updatedArray.length === 9) {
            postThisWeekData.push(updatedArray);
            updatedArray = [];
          }
        }
      }
      upDateFreeTime(postThisWeekData).then(
        (res) => {
          console.log(res);
          message.success("更新本周状态成功")
        }

      )
    }
    else {
      let temporyArray = [];
      let postNextWeekData = [];
      for (let colIndex = 1; colIndex <= 5; colIndex++) {
        for (let rowIndex = 1; rowIndex <= 9; rowIndex++) {
          let time = judgeTime(rowIndex)
          let date = judegNextWeekDate(colIndex)
          const cellKey = `${rowIndex + 1}-${colIndex + 1}`;
          const idle = clickedCells.includes(cellKey) ? true : false;
          const data =
          {
            id: (nextWeekData[0].id - 1) + (colIndex - 1) * 9 + rowIndex,
            // userId: thisWeekData[0].userId,
            date: date,
            time: time,
            idle: idle
          }

          temporyArray.push(data);

          if (temporyArray.length === 9) {
            postNextWeekData.push(temporyArray);
            temporyArray = [];
          }
        }
      }
      upDateFreeTime(postNextWeekData).then(
        (res) => {
          console.log(res);
          message.success("更新下周状态成功")
        }
      )
    }
    window.location.reload();
  }

  // 渲染Grid
  const renderGrid = () => {

    const grid = [];
    {/* col列 row行 */ }
    for (let colIndex = 0; colIndex < 6; colIndex++) {
      const col = [];
      for (let rowIndex = 0; rowIndex < 10; rowIndex++) {
        // 为每个cell添加位置标记如1-1 1-2
        const cellKey = `${rowIndex + 1}-${colIndex + 1}`;
        // 是否为第一列
        const isCol1 = colIndex === 0 && rowIndex >= 0;
        // 是否为第一行第一个
        const isRow1Col1 = colIndex === 0 && rowIndex === 0

        // 是否为晚上
        // const isNightCell = cellKey.split('-')[0] > 8 && cellKey.split('-')[1] > 1
        // 是否为可点击区域 2-2开始
        const isAbleClick = colIndex > 0 && rowIndex > 0
        // 是否为空闲判断
        const isFree = (cellKey) => {
          return clickedCells.includes(cellKey);
        };
        // 是否为显示星期
        const isWeek = colIndex > 0 && rowIndex === 0;
        // 拆分日期和星期几
        const timeArrayElement = value === 1 ? timeArray[colIndex - 1] : timeArray[colIndex + 4];
        const [date, day] = timeArrayElement ? timeArrayElement.split('-') : ['', ''];

        col.push(
          <div
            className={`cell ${isCol1 ? 'dayTime' : ''} ${isAbleClick && isFree(cellKey) ? 'free' : ''}`}
            key={cellKey}
            onClick={() => isAbleClick && handleCellClick(cellKey)}
          >
            {
              // 1-1 切换本周与下周
              isRow1Col1 ? (<ToggleWeek />)
                : isCol1 ? (dates[rowIndex - 1])
                  : isWeek ? (
                    <div className='weekTime'>
                      <span>{date}</span><br />
                      <span>{day}</span>
                    </div>
                  )
                    : ""
            }
          </div>
        );
      }
      grid.push(
        <div className='col' key={`col-${colIndex + 1}`}>
          {col}
        </div>
      );
    }

    return grid;
  };
  return (<>
    <div className='grid'>
      {renderGrid()}
    </div>
    <div className='buttonContainer'>
      <div className='queryButton'>
        <Button type='primary' onClick={handleQueryButtonClick}>
          点击查询空闲状态
        </Button>
      </div>
      <div className='updateButton'>
        <Button type='primary' onClick={handleSetStatusClick}>
          提交更新
        </Button>
      </div>
    </div>

  </>
  );
};

export default Freetime;